import { Body, Controller, Delete, Param, Post, Put, UseGuards } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ResponseBodyDto } from 'src/dto';
import { queryPagination, toFuzzyParams, updateOneById } from 'src/utils';
import { JwtAuthGuard } from 'src/common/guards';
import { CurrentUser } from 'src/common/paramDecorators';
import { Users, UsersDocument } from 'src/db/schemas';
import { DeleteDto } from 'src/dto/delete.dto';
import { CreateUserDto } from './dto/create-user.dto';
import { UsersService } from './users.service';
import { UpdateUserDto } from './dto';
import { QueryUsersPaginationDto } from './dto/query-users.dto';
import { ReturnUsersPaginationDto } from './dto/return-users.dto';

@ApiTags('用户')
@Controller('users')
@ApiBearerAuth('Authorization')
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    @InjectModel(Users.name) private usersModel: Model<UsersDocument>,
  ) { }

  @Post('getUsersPage')
  @ApiOkResponse({
    description: '用户分页',
    type: ReturnUsersPaginationDto,
  })
  @ApiOperation({
    summary: '获取用户分页',
  })
  getWebsitePagination(@Body() queryUsersDto: QueryUsersPaginationDto) {
    const { pageSize, current, ...other } = queryUsersDto;
    return queryPagination(
      this.usersModel,
      toFuzzyParams(other),
      {
        pageSize,
        current,
      },
      {},
      {
        password: 0,
      }
    );
  }

  @Post('getAll')
  getAll(@CurrentUser() currentUser: GolbalTypes.JWTUser) {
    return this.usersService.getAll();
  }

  @Post('addOne')
  addOne(@Body() createUserDto: CreateUserDto) {
    return this.usersService.addOne(createUserDto);
  }

  @Delete('delete')
  delete(@Body() deleteDto: DeleteDto) {
    return this.usersService.delete(deleteDto);
  }

  @Put('updateUser/:_id')
  @ApiOkResponse({
    description: '更新结果',
    type: ResponseBodyDto,
  })
  @ApiOperation({
    summary: '更新用户信息',
  })
  updateWebsiteType(
    @Param('_id') _id: string,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    updateOneById(this.usersModel, _id, updateUserDto);
  }
}
